<?php
/**
 * Created by PhpStorm.
 * User: Gustav
 * Date: 2018/7/27
 * Time: 20:11
 */

namespace app\user\controller;

use app\common\controller\GlobalVariable;
use app\common\controller\UserController;
use app\common\service\Validate;
use app\user\model\User;
use think\Request;
use think\Db;
use think\Session;

class Favor extends UserController
{
    /**
     * 收藏文章
     */
    public function collect()
    {
        $action_time = input('post.action_time');
        $thesis_id = input('post.thesis_id');
        $find2 = Db::table('xwd_doc_thesis')->where('thesis_id', $thesis_id)->find();
        if ($find2) {
            $token = Request::instance()->header('token');
            $find = Db::table('xwd_user_login_info')->where('token', $token)->find();
            $user_id = json_encode($find['user_id']);
            $find3 = Db::table('xwd_user_behavior')->where(['user_id' => $user_id, 'thesis_id' => $thesis_id, 'action_type' => 4])->find();
            if ($find3) {
                return GlobalVariable::promptErrorByJSON("错误", 500, "已在收藏!");
            } else {
                Db::table('xwd_user_behavior')->insert(['user_id' => $user_id, 'thesis_id' => $thesis_id, 'action_time' => $action_time, 'action_type' => 4]);
                Db::table('xwd_user_recommend_history')->where(['user_id' => $user_id, 'thesis_id' => $thesis_id])->update(['type' => 1]);
            }
            return GlobalVariable::promptErrorByJSON("成功", 200, "成功");
        } else {
            return GlobalVariable::promptErrorByJSON("错误", 500, "未找到该文章!");
        }

    }

    /**
     * 取消收藏文章
     */
    public function cancelCollect()
    {
        $thesis_id = input('post.thesis_id');
        $token = Request::instance()->header('token');
        $find = Db::table('xwd_user_login_info')->where('token', $token)->find();
        $user_id = json_encode($find['user_id']);
        $if = Db::table('xwd_user_behavior')->where(['user_id' => $user_id, 'thesis_id' => $thesis_id, 'action_type' => 4])->find();
        if ($if) {
            Db::table('xwd_user_behavior')->where(['user_id' => $user_id, 'thesis_id' => $thesis_id, 'action_type' => 4])->delete();
            return GlobalVariable::promptErrorByJSON("成功", 200, "成功");
        } else {
            return GlobalVariable::promptErrorByJSON("失败", 500, "未找到该收藏文章");
        }
    }

    /**
     * 喜好文章
     */
    public function like()
    {
        $action_time = input('post.action_time');
        $thesis_id = input('post.thesis_id');
        $find2 = Db::table('xwd_doc_thesis')->where('thesis_id', $thesis_id)->find();
        if ($find2) {
            $token = Request::instance()->header('token');
            $find = Db::table('xwd_user_login_info')->where('token', $token)->find();
            $user_id = json_encode($find['user_id']);
            $find3 = Db::table('xwd_user_behavior')->where(['user_id' => $user_id, 'thesis_id' => $thesis_id, 'action_type' => 3])->find();
            if ($find3) {
                return GlobalVariable::promptErrorByJSON("错误", 500, "已在喜好!");
            } else {
                Db::table('xwd_user_behavior')->insert(['user_id' => $user_id, 'thesis_id' => $thesis_id, 'action_time' => $action_time, 'action_type' => 3]);
                Db::table('xwd_user_recommend_history')->where(['user_id' => $user_id, 'thesis_id' => $thesis_id])->update(['type' => 1]);
            }
            return GlobalVariable::promptErrorByJSON("成功", 200, "成功");
        } else {
            return GlobalVariable::promptErrorByJSON("错误", 500, "未找到该文章!");
        }

    }

    /**
     * 取消喜好文章
     */
    public function cancelLike()
    {
        $thesis_id = input('post.thesis_id');
        $token = Request::instance()->header('token');
        $find = Db::table('xwd_user_login_info')->where('token', $token)->find();
        $user_id = json_encode($find['user_id']);
        $if = Db::table('xwd_user_behavior')->where(['user_id' => $user_id, 'thesis_id' => $thesis_id, 'action_type' => 3])->find();
        if ($if) {
            Db::table('xwd_user_behavior')->where(['user_id' => $user_id, 'thesis_id' => $thesis_id, 'action_type' => 3])->delete();
            return GlobalVariable::promptErrorByJSON("成功", 200, "成功");
        } else {
            return GlobalVariable::promptErrorByJSON("失败", 500, "未找到该喜好文章");
        }
    }

    /**
     * 不感兴趣文章
     */
    public function dislike()
    {
        $action_time = input('post.action_time');
        $thesis_id = input('post.thesis_id');
        $find2 = Db::table('xwd_doc_thesis')->where('thesis_id', $thesis_id)->find();
        if ($find2) {
            $token = Request::instance()->header('token');
            $find = Db::table('xwd_user_login_info')->where('token', $token)->find();
            $user_id = json_encode($find['user_id']);
            $find3 = Db::table('xwd_user_behavior')->where(['user_id' => $user_id, 'thesis_id' => $thesis_id, 'action_type' => 1])->find();
            if ($find3) {
                return GlobalVariable::promptErrorByJSON("错误", 500, "已在不感兴趣!");
            } else {
                Db::table('xwd_user_behavior')->insert(['user_id' => $user_id, 'thesis_id' => $thesis_id, 'action_time' => $action_time, 'action_type' => 1]);
                Db::table('xwd_user_recommend_history')->where(['user_id' => $user_id, 'thesis_id' => $thesis_id])->update(['type' => 1]);
            }
            return GlobalVariable::promptErrorByJSON("成功", 200, "成功");
        } else {
            return GlobalVariable::promptErrorByJSON("错误", 500, "未找到该文章!");
        }
    }

    /**
     * 取消不感兴趣文章
     */
    public function cancelDislike()
    {
        $thesis_id = input('post.thesis_id');
        $token = Request::instance()->header('token');
        $find = Db::table('xwd_user_login_info')->where('token', $token)->find();
        $user_id = json_encode($find['user_id']);
        $if = Db::table('xwd_user_behavior')->where(['user_id' => $user_id, 'thesis_id' => $thesis_id, 'action_type' => 1])->find();
        if ($if) {
            Db::table('xwd_user_behavior')->where(['user_id' => $user_id, 'thesis_id' => $thesis_id, 'action_type' => 1])->delete();
            return GlobalVariable::promptErrorByJSON("成功", 200, "成功");
        } else {
            return GlobalVariable::promptErrorByJSON("失败", 500, "未找到该文章");
        }
    }

    /**
     * 切除判断是否喜欢
     */
    public function dislikeJudge()
    {
        $thesis_id = input('post.thesis_id');
        $token = Request::instance()->header('token');
        $find = Db::table('xwd_user_login_info')->where('token', $token)->find();
        $user_id = json_encode($find['user_id']);
        $like = Db::table('xwd_user_behavior')->where(['user_id' => $user_id, 'thesis_id' => $thesis_id, 'action_type' => 1])->find();
        if ($like) {
            $change = Db::table('xwd_user_scan_list')->where('token', $token)->find();
            $list = json_decode($change['thesis_list']);
            $num = count($list, 0);
            $list2 = [];
            for ($i = 0, $k = 0; $i < $num; $i++) {
                if ($list[$i] == $thesis_id) {
                    continue;
                }
                $list2[$k++] = $list[$i];
            }
            Db::table('xwd_user_scan_list')->where('token', $token)->update(['thesis_list' => json_encode($list2)]);
            return GlobalVariable::promptErrorByJSON("成功", 200, "成功");
        } else {
            return GlobalVariable::promptErrorByJSON("成功", 200, "成功");
        }
    }

    /**
     * 收藏文章返回
     */
    public function getCollection()
    {
        $token = Request::instance()->header('token');
        $find = Db::table('xwd_user_login_info')->where('token', $token)->find();
        $user_id = json_encode($find['user_id']);
        $data = Db::table('xwd_user_behavior')->where(['user_id' => $user_id, 'action_type' => 4])->select();
        if ($data) {
            $thesis = [];
            $num = count($data, 0);
            for ($i = 0; $i < $num; $i++) {
                $thesis_id = $data[$i]['thesis_id'];
                $find = Db::table('xwd_doc_thesis')->where('thesis_id', $thesis_id)->find();
                array_push($thesis, $find);
            }
            return GlobalVariable::promptData($thesis);
        } else {
            return GlobalVariable::promptErrorByJSON("错误", 500, "您还未收藏文章!");
        }
    }

    /**
     * 发表文章返回
     */
    public function getOwnThesis()
    {
        $token = Request::instance()->header('token');
        $find = Db::table('xwd_user_login_info')->where('token', $token)->find();
        $user_id = json_encode($find['user_id']);
        $data = Db::table('xwd_user_thesis')->where('user_id', $user_id)->select();
        if ($data) {
            $thesis = [];
            $num = count($data, 0);
            for ($i = 0; $i < $num; $i++) {
                $thesis_id = $data[$i]['thesis_id'];
                $find = Db::table('xwd_doc_thesis')->where('thesis_id', $thesis_id)->find();
                array_push($thesis, $find);
            }
            return GlobalVariable::promptData($thesis);
        } else {
            return GlobalVariable::promptErrorByJSON("错误", 500, "您还未发表文章!");
        }
    }

    /**
     * 推荐过的文章单独记录(我写代码以来写过的最蠢的逻辑)
     */

    public function recommendCheck($user_id, $list)
    {
        $time = time();
        $num = count($list, 0);
        for ($i = 0; $i < $num; $i++) {
            $thesis_id = json_encode($list[$i]['thesis_id']);
            Db::table('xwd_user_recommend_history')->insert(['user_id' => $user_id, 'thesis_id' => $thesis_id, 'action_time' => $time]);
        }
        return true;
    }

    public function recommendCheck2($user_id, $list)
    {
        $time = time();
        $num = count($list, 0);
        for ($i = 0; $i < $num; $i++) {
            $thesis_id = json_encode($list[$i]);
            Db::table('xwd_user_recommend_history')->insert(['user_id' => $user_id, 'thesis_id' => $thesis_id, 'action_time' => $time]);
        }
        return true;
    }

    public function recommendCheck3($user_id, $list)
    {
        $time = time();
        $num = count($list, 0);
        for ($i = 0; $i < $num; $i++) {
            $thesis_id = $list[$i];
            settype($thesis_id, 'int');
            Db::table('xwd_user_recommend_history')->insert(['user_id' => $user_id, 'thesis_id' => $thesis_id, 'action_time' => $time]);
        }
        return true;
    }

    /**
     * 推荐文章返回
     */

    public function getRecommend()
    {
        $thesis_num = input('get.thesis_num');
        if (!$thesis_num) {
            $thesis_num = 5;
        }
        settype($thesis_num, 'int');
        $token = Request::instance()->header('token');
        $isTop = input('get.isTop');
        $find = Db::table('xwd_user_login_info')->where('token', $token)->find();
        $user_id = json_encode($find['user_id']);
        $data = Db::table('xwd_user_recommend')->where('user_id', $user_id)->find();
        if ($data) {
            $thesis_list0 = json_decode($data['thesis_list']);
            $num0 = count($thesis_list0, 0);
            $thesis_list = [];
            for ($i = 0, $p = 0; $i < $num0; $i++) {
                $ifRec = Db::table('xwd_user_recommend_history')->where(['user_id' => $user_id, 'thesis_id' => $thesis_list0[$i]])->find();
                if ($ifRec) { //604800一周
                    if ($ifRec['type'] == 0) {
                        $action_time = $ifRec['action_time'];
                        if (time() - $action_time <= 604800) {
                            continue;
                        }
                    } else if ($ifRec['type'] == 1) {
                        continue;
                    }
                }
                $thesis_list[$p++] = $thesis_list0[$i];
            }
            $num = count($thesis_list, 0);
            if ($num > $thesis_num) {
                $real = [];//实际推荐
                $remain = []; //剩下未推荐的文章
                for ($i = 0; $i < $thesis_num; $i++) {
                    $real[$i] = $thesis_list[$i];
                }
                for ($j = $i, $k = 0; $j < $num; $j++) {
                    $remain[$k++] = $thesis_list[$j];
                }
                Db::table('xwd_user_recommend')->where('user_id', $user_id)->update(['thesis_list' => json_encode($remain)]);
                $this->insertList($isTop, $real);
                $thesis = [];
                for ($i = 0; $i < $thesis_num; $i++) {
                    $thesis_id = $real[$i];
                    $a = Db::table('xwd_doc_thesis')->where('thesis_id', $thesis_id)->find();
                    $journal_id = $a["journal_id"];
                    $list2 = Db::table('xwd_doc_journal')->where('journal_id', $journal_id)->find();
                    $a["periodical"] = $list2["periodical"];
                    array_push($thesis, $a);
                }
                $this->recommendCheck($user_id, $thesis);
                return GlobalVariable::promptData($thesis);
            } else if ($num == $thesis_num) {
                $this->insertList($isTop, $thesis_list);
                $thesis = [];
                for ($i = 0; $i < $num; $i++) {
                    $thesis_id = $thesis_list[$i];
                    $a = Db::table('xwd_doc_thesis')->where('thesis_id', $thesis_id)->find();
                    $journal_id = $a["journal_id"];
                    $list2 = Db::table('xwd_doc_journal')->where('journal_id', $journal_id)->find();
                    $a["periodical"] = $list2["periodical"];
                    array_push($thesis, $a);
                }
                $this->recommendCheck($user_id, $thesis);
                Db::table('xwd_user_recommend')->where('user_id', $user_id)->delete();
                return GlobalVariable::promptData($thesis);
            } else if ($num < $thesis_num) {
                $thesis = [];
                for ($i = 0; $i < $num; $i++) {
                    $thesis_id = $thesis_list[$i];
                    $a = Db::table('xwd_doc_thesis')->where('thesis_id', $thesis_id)->find();
                    $journal_id = $a["journal_id"];
                    $list2 = Db::table('xwd_doc_journal')->where('journal_id', $journal_id)->find();
                    $a["periodical"] = $list2["periodical"];
                    array_push($thesis, $a);
                }
                $others = $thesis_num - $num;
                $real_num = count($thesis, 0);
                $rand_ids = [];
                $select = [];
                for ($i = 0; $i < $others; $i++) {
                    while (1) {
                        $findO = Db::table('xwd_doc_thesis')->orderRaw('rand()')->limit($others)->find();
                        $ifRec = Db::table('xwd_user_recommend_history')->where(['user_id' => $user_id, 'thesis_id' => $findO['thesis_id']])->find();
                        if (!$ifRec) {
                            break;
                        } else {
                            $action_time = $ifRec['action_time'];
                            if (time() - $action_time <= 604800) {
                                break;
                            }
                        }
                    }
                    array_push($select, $findO);
                }
//                $select = Db::table('xwd_doc_thesis')->orderRaw('rand()')->limit($others)->select();
                for ($i = 0; $i < $others; $i++) {
                    $rand_ids[$i] = $select[$i]["thesis_id"];
                    settype($rand_ids[$i], 'string');
                    $journal_id = $select[$i]["journal_id"];
                    $list2 = Db::table('xwd_doc_journal')->where('journal_id', $journal_id)->select();
                    $select[$i]["periodical"] = $list2[0]["periodical"];
                    $thesis[$real_num++] = $select[$i];
                }
                $thesis_list = array_merge($thesis_list, $rand_ids);
                $this->recommendCheck3($user_id, $thesis_list);
                $this->insertList($isTop, $thesis_list);
                Db::table('xwd_user_recommend')->where('user_id', $user_id)->delete();
                return GlobalVariable::promptData($thesis);
            }
        } else {
            $select = Db::table('xwd_doc_thesis')->orderRaw('rand()')->limit($thesis_num)->select();
            for ($i = 0; $i < $thesis_num; $i++) {
                $journal_id = $select[$i]["journal_id"];
                $list2 = Db::table('xwd_doc_journal')->where('journal_id', $journal_id)->select();
                $select[$i]["periodical"] = $list2[0]["periodical"];
            }
            $thesis_list = [];
            for ($i = 0; $i < $thesis_num; $i++) {
                $thesis_list[$i] = $select[$i]["thesis_id"];
            }
            $this->insertList($isTop, $thesis_list);
            $this->recommendCheck2($user_id, $thesis_list);
            return GlobalVariable::promptData($select);
        }
    }

    /**
     * 用户浏览列表
     */

    public function insertList($isTop, $list)
    {
        $token = Request::instance()->header('token');
        $a = Db::table('xwd_user_login_info')->where('token', $token)->find();
        $user_id = json_encode($a['user_id']);
        if ($isTop == 0) {
            $find = Db::table('xwd_user_scan_list')->where('token', $token)->find();
            if ($find) {
                $re_list = json_decode($find['thesis_list'], true);
                $list = array_merge($re_list, $list);
                Db::table('xwd_user_scan_list')->where('token', $token)->update(['thesis_list' => json_encode($list), 'user_id' => $user_id]);
                return true;
            } else {
                Db::table('xwd_user_scan_list')->insert(['token' => $token, 'thesis_list' => json_encode($list), 'user_id' => $user_id]);
                return true;
            }
        } else if ($isTop == 1) {
            $find = Db::table('xwd_user_scan_list')->where('token', $token)->find();
            if ($find) {
                $re_list = json_decode($find['thesis_list'], true);
                $list = array_merge($list, $re_list);
                Db::table('xwd_user_scan_list')->where('token', $token)->update(['thesis_list' => json_encode($list), 'user_id' => $user_id]);
                return true;
            } else {
                Db::table('xwd_user_scan_list')->insert(['token' => $token, 'thesis_list' => json_encode($list), 'user_id' => $user_id]);
                return true;
            }
        } else {
            return GlobalVariable::promptErrorByJSON("错误", 500, "传入参数错误!");
        }
    }

    /**
     * 文章列表
     */

    public function usualList()
    {
        $token = Request::instance()->header('token');
        $find = Db::table('xwd_user_scan_list')->where('token', $token)->find();
        if ($find) {
            $list = json_decode($find['thesis_list'], true);
            $num = count($list, 0);
            $thesis = [];
            for ($i = 0; $i < $num; $i++) {
                $a = Db::table('xwd_doc_thesis')->where('thesis_id', $list[$i])->find();
                $journal_id = $a['journal_id'];
                $b = Db::table('xwd_doc_journal')->where('journal_id', $journal_id)->find();
                $a['periodical'] = $b['periodical'];
                array_push($thesis, $a);
            }
            return GlobalVariable::promptData($thesis);
        } else {
            $this->getRecommend();
        }
    }

    /**
     * 判断文章是否收藏、喜好、不感兴趣
     */

    public function thesisJudge()
    {
        $type = input('post.type');
        if ($type == 3) {
            $this->like();
        } else if ($type == 1) {
            $this->dislike();
        } else if ($type == 4) {
            $this->collect();
        } else if ($type == 2) {
            $this->userAct();
        } else {
            return GlobalVariable::promptErrorByJSON("错误", 500, "参数传输错误!");
        }
    }

    /**
     * 取消文章收藏、喜好、不感兴趣
     */
    public function thesisCancel()
    {
        $type = input('post.type');
        if ($type == 3) {
            $this->cancelLike();
        } else if ($type == 1) {
            $this->cancelDislike();
        } else if ($type == 4) {
            $this->cancelCollect();
        } else {
            return GlobalVariable::promptErrorByJSON("错误", 500, "参数传输错误!");
        }
    }

    /**
     * 判断当前文章状态(喜好、不感兴趣、收藏)
     */
    public function thesisStatus()
    {
        $s = ['like' => false, 'dislike' => false, 'collect' => false];
        $thesis_id = input('post.thesis_id');
        $find = Db::table('xwd_doc_thesis')->where('thesis_id', $thesis_id)->find();
        if ($find) {
            $token = Request::instance()->header('token');
            $find2 = Db::table('xwd_user_login_info')->where('token', $token)->find();
            $user_id = json_encode($find2['user_id']);
            $findlike = Db::table('xwd_user_behavior')->where(['user_id' => $user_id, 'thesis_id' => $thesis_id, 'action_type' => 3])->find();
            if ($findlike) {
                $s['like'] = true;
            }
            $finddislike = Db::table('xwd_user_behavior')->where(['user_id' => $user_id, 'thesis_id' => $thesis_id, 'action_type' => 1])->find();
            if ($finddislike) {
                $s['dislike'] = true;
            }
            $findcollect = Db::table('xwd_user_behavior')->where(['user_id' => $user_id, 'thesis_id' => $thesis_id, 'action_type' => 4])->find();
            if ($findcollect) {
                $s['collect'] = true;
            }
            return GlobalVariable::promptData($s);
        }
        return GlobalVariable::promptErrorByJSON("错误", 500, "未找到该文章!");
    }

    /**
     * 记录用户点击文章
     */

    public function userAct()
    {
        $thesis_id = input('post.thesis_id');
        $action_time = input('post.action_time');
        $find = Db::table('xwd_doc_thesis')->where('thesis_id', $thesis_id)->find();
        if ($find) {
            $token = Request::instance()->header('token');
            $find2 = Db::table('xwd_user_login_info')->where('token', $token)->find();
            $user_id = json_encode($find2['user_id']);
            Db::table('xwd_user_behavior')->insert(['user_id' => $user_id, 'thesis_id' => $thesis_id, 'action_time' => $action_time, 'action_type' => 2]);
            Db::table('xwd_user_recommend_history')->where(['user_id' => $user_id, 'thesis_id' => $thesis_id])->update(['type' => 1]);
            return GlobalVariable::promptErrorByJSON("成功", 200, "成功");
        } else {
            return GlobalVariable::promptErrorByJSON("错误", 500, "未找到该文章!");
        }
    }

    /**
     * 返回用户浏览记录
     */

    public function historyAct()
    {
        $token = Request::instance()->header('token');
        $find = Db::table('xwd_user_login_info')->where('token', $token)->find();
        $user_id = json_encode($find['user_id']);
        $select = Db::table('xwd_user_behavior')->where(['user_id' => $user_id, 'action_type' => 2])->order('action_time desc')->select();
        if ($select) {
            $thesis = [];
            $num = count($select, 0);
            for ($i = 0; $i < $num; $i++) {
                $thesis_id = $select[$i]['thesis_id'];
                $find = Db::table('xwd_doc_thesis')->where('thesis_id', $thesis_id)->find();
                array_push($thesis, $find);
            }
            return GlobalVariable::promptData($thesis);
        } else {
            return GlobalVariable::promptErrorByJSON("错误", 500, "您不存在浏览记录，请先浏览文章!");
        }
    }

    /**
     * 返回收藏文章与浏览记录
     */

    public function collectOrAct()
    {
        $type = input('get.type');
//        1-浏览记录 2-收藏文章
        if ($type == 1) {
            $this->historyAct();
        } else if ($type == 2) {
            $this->getCollection();
        }
    }


    /**
     * 执行shell
     */

    public function countRecommend()
    {
        $token = Request::instance()->header('token');
        $find = Db::table('xwd_user_login_info')->where('token', $token)->find();
        $user_id = json_encode($find['user_id']);
        $findK = Db::table('xwd_user_keyword')->where('user_id',$user_id)->find();
        var_dump(json_decode($findK));
        $data1 = "Flash memeory,Energy density";
        $data = exec("cd /www/wwwroot/paper.ujnxgzx.com/python/production; python3 itemcf.py " . $data1);
        $data = json_decode($data, true);
        $num = count($data["data"], 0);
        $thesis = [];
        $ids = [];
        for ($i = 0; $i < $num; $i++) {
            $thesis_id = $data["data"][$i]["id"];
            $ids[$i] = $thesis_id;
            $find = Db::table('xwd_doc_thesis')->where('thesis_id', $thesis_id)->find();
            $journal_id = $find['journal_id'];
            $b = Db::table('xwd_doc_journal')->where('journal_id', $journal_id)->find();
            $find['periodical'] = $b['periodical'];
            array_push($thesis, $find);
        }
        $ids = json_encode($ids);
        Db::table('xwd_user_recommend')->insert(['user_id' => $user_id, 'thesis_list' => $ids, 'time' => time()]);
        return GlobalVariable::promptData($thesis);
    }
}